package com.elite.groovy.callback

import cn.com.tpqn.sessionDetail
import com.elite.groovy.util.EliteBean
import groovy.json.JsonSlurper
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat

public class autoTPQNSessionDetail implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(autoTPQNSessionDetail.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		log.debug("查询获取SESSION_DETAIL的数据开始执行...");
		String reJson = "";

		String code = "0";
		int pages = 0;
		int pagenum = 0;

		// 开始时间时间戳
		def startTimeString = deal(-100);
		def startTime = dateToStamp(startTimeString);
		log.debug("获取时间开始时间(时间/时间戳):" + startTimeString + "/" + startTime);

		// 结束时间时间戳
		def endTimeString = deal(0);
		def endTime = dateToStamp(endTimeString);
		log.debug("获取时间结束时间(时间/时间戳):" + endTimeString + "/" + endTime);

		while(code=="0") {
			pages=pages+1;
			reJson = sessionDetail.main(startTime, endTime, pages.toString());
			log.debug("当前获取页数:"+pages + " 当前返回结果:"+reJson);

			//解析返回結果
			def root=new JsonSlurper().parseText(reJson);
			code = root.code;
			pagenum = root.result.size();
			if(pagenum > 0 && code == "0") {
				log.debug("获取SESSION_DETAIL的数据成功...");
				toDoGet(eliteBean, callBack, map, paramString, reJson);
			}
		};
		log.debug("查询获取SESSION_DETAIL的数据结束执行...");

	}

	static toDoGet(EliteBean eliteBean, String callBack, Map map, String paramString, String reJson) {

		//处理主数据
		JSONObject jsonObject = new JSONObject(reJson);
		JSONArray dataArray = new JSONArray(GetJV(jsonObject, "result"));
		int dataArrayLen = dataArray.length();

		log.info("Data Result size:" + dataArrayLen);
		JSONObject dataObject = null;
		for(int i = 0;i<dataArrayLen;i++) {
			dataObject = dataArray.getJSONObject(i);
			def ssession_id = GetJV(dataObject, "session_id");
			log.debug("Deal Data session_id:" + ssession_id);
			def sql = "Select Count(*) as Count From TP_QN_SessionDetail Where session_id ='" + ssession_id + "'";

			def sqlResult=eliteBean.chaxun_sql(sql, 'dataSource');
			def Countnum =sqlResult.get(0).get("Count");
			log.debug("Countnumi:"+Countnum);

			if(Countnum<=0){
				def rec_guid = UUID.randomUUID().toString();
				def start_time = stampToDate(GetJV(dataObject, "start_time"));
				def end_time = stampToDate(GetJV(dataObject, "end_time"));
				def session_id = GetJV(dataObject, "session_id");
				def agent_id = GetJV(dataObject, "agent_id");
				def agent_name = GetJV(dataObject, "agent_name");
				def agent_dn = GetJV(dataObject, "agent_dn");
				def skill_id = GetJV(dataObject, "skill_id");
				def skill_name = GetJV(dataObject, "skill_name");
				def local_url = GetJV(dataObject, "local_url");
				def remote_url = GetJV(dataObject, "remote_url");
				def ivr_duration = GetJV(dataObject, "ivr_duration");
				def alert_duration = GetJV(dataObject, "alert_duration");
				def alert_duration_agent = GetJV(dataObject, "alert_duration_agent");
				def queue_duration = GetJV(dataObject, "queue_duration");
				def talk_duration = GetJV(dataObject, "talk_duration");
				def acw_duration = GetJV(dataObject, "acw_duration");
				def end_type = GetJV(dataObject, "end_type");
				def call_type = GetJV(dataObject, "call_type");
				def dial_times = GetJV(dataObject, "dial_times");
				def ivr_time = GetJV(dataObject, "ivr_time");
				def alter_time = GetJV(dataObject, "alter_time");
				def transfer_agent_time = GetJV(dataObject, "transfer_agent_time");
				def transfer_queue_time = GetJV(dataObject, "transfer_queue_time");
				def transfer_altering_time = GetJV(dataObject, "transfer_altering_time");
				def local_url_wx = GetJV(dataObject, "local_url_wx");
				def remote_url_wx = GetJV(dataObject, "remote_url_wx");
				def campaign_id = GetJV(dataObject, "campaign_id");
				def dest_ani = GetJV(dataObject, "dest_ani");
				def end_reason = GetJV(dataObject, "end_reason");
				def global_serial_num = GetJV(dataObject, "global_serial_num");
				def exdata1 = GetJV(dataObject, "exdata1");
				def exdata2 = GetJV(dataObject, "exdata2");
				def exdata3 = GetJV(dataObject, "exdata3");
				def exdata4 = GetJV(dataObject, "exdata4");
				def exdata5 = GetJV(dataObject, "exdata5");
				def exdata6 = GetJV(dataObject, "exdata6");
				def exdata7 = GetJV(dataObject, "exdata7");
				def exdata8 = GetJV(dataObject, "exdata8");
				def exdata9 = GetJV(dataObject, "exdata9");
				def exdata10 = GetJV(dataObject, "exdata10");
				def entId = GetJV(dataObject, "entId");

				sql="insert into TP_QN_SESSIONDETAIL (REC_GUID, START_TIME, END_TIME, SESSION_ID, AGENT_ID, AGENT_NAME, AGENT_DN, SKILL_ID, SKILL_NAME, LOCAL_URL, REMOTE_URL, IVR_DURATION, ALERT_DURATION, ALERT_DURATION_AGENT, QUEUE_DURATION, TALK_DURATION, ACW_DURATION, END_TYPE, CALL_TYPE, DIAL_TIMES, IVR_TIME, ALTER_TIME, TRANSFER_AGENT_TIME, TRANSFER_QUEUE_TIME, TRANSFER_ALTERING_TIME, LOCAL_URL_WX, REMOTE_URL_WX, CAMPAIGN_ID, DEST_ANI, END_REASON, GLOBAL_SERIAL_NUM, EXDATA1, EXDATA2, EXDATA3, EXDATA4, EXDATA5, EXDATA6, EXDATA7, EXDATA8, EXDATA9, EXDATA10, ENTID, SYNC_TIME) values ('"+ rec_guid +"', '"+start_time+"','"+end_time+"','"+session_id+"','"+agent_id+"','"+agent_name+"','"+agent_dn+"','"+skill_id+"','"+skill_name+"','"+local_url+"','"+remote_url+"','"+ivr_duration+"','"+alert_duration+"','"+alert_duration_agent+"','"+queue_duration+"','"+talk_duration+"','"+acw_duration+"','"+end_type+"','"+call_type+"','"+dial_times+"','"+ivr_time+"','"+alter_time+"','"+transfer_agent_time+"','"+transfer_queue_time+"','"+transfer_altering_time+"','"+local_url_wx+"','"+remote_url_wx+"','"+campaign_id+"','"+dest_ani+"','"+end_reason+"','"+global_serial_num+"','"+exdata1+"','"+exdata2+"','"+exdata3+"','"+exdata4+"','"+exdata5+"','"+exdata6+"','"+exdata7+"','"+exdata8+"','"+exdata9+"','"+exdata10+"','"+entId+"',sysdate)";

				sqlResult=eliteBean.update(sql, 'dataSource');

			}
		}

	}

	// 在当前时间的基础上加减小时得到变化后的时间
	static String deal(int addHours) {

		String oneHoursAgoTime = "";
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.HOUR, addHours);
		Date dt1 = rightNow.getTime();
		oneHoursAgoTime = sdf.format(dt1);
		return oneHoursAgoTime;
	}

	/*
	 * 将时间字符串转换为时间戳
	 */
	static String dateToStamp(String s) {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = null;
		try {
			date = simpleDateFormat.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		long ts = date.getTime();
		res = String.valueOf(ts);
		return res;
	}

	/*
	 * 将时间戳转换为时间字符串
	 */
	static String stampToDate(String s) {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		long lt = new Long(s);
		Date date = new Date(lt);
		res = simpleDateFormat.format(date);
		return res;
	}

	/*
	 * 解析Json字符串
	 */
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				log.warn("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}else {
				log.debug("GetJV 获取参数值-" + getKey + ":" + Rev_Value);
			}
		}
		return Rev_Value;
	}

}